<template>
  <div class="order-management">
    <h2>{{ $t('message.orderManagement') }}</h2>
    
    <div class="order-filters">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select 
            v-model="filter.orderType" 
            :placeholder="$t('message.orderType')" 
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="type in orderTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select 
            v-model="filter.status" 
            :placeholder="$t('message.status')" 
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input 
            v-model="filter.userId" 
            :placeholder="$t('message.userId')" 
            clearable
          />
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="loadOrders">{{ $t('message.search') }}</el-button>
          <el-button @click="resetFilters">{{ $t('message.reset') }}</el-button>
        </el-col>
      </el-row>
    </div>
    
    <div class="order-actions">
      <el-button type="primary" @click="openAddOrderDialog">{{ $t('message.addOrder') }}</el-button>
    </div>
    
    <el-table
      :data="orders"
      style="width: 100%"
      :default-sort="{ prop: 'createdAt', order: 'descending' }"
    >
      <el-table-column prop="orderId" :label="$t('message.orderId')" width="200" show-overflow-tooltip align="left" header-align="left" />
      <el-table-column prop="userId" :label="$t('message.userId')" width="150" align="left" header-align="left" />
      <el-table-column prop="orderType" :label="$t('message.orderType')" width="120" align="left" header-align="left">
        <template #default="scope">
          {{ getOrderTypeLabel(scope.row.orderType) }}
        </template>
      </el-table-column>
      <el-table-column prop="amount" :label="$t('message.amount')" width="100" align="left" header-align="left">
        <template #default="scope">
          ¥{{ scope.row.amount }}
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="$t('message.status')" width="120" align="left" header-align="left">
        <template #default="scope">
          <el-tag 
            :type="getStatusType(scope.row.status)"
            disable-transitions
          >
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="transactionId" :label="$t('message.transactionId')" width="200" show-overflow-tooltip align="left" header-align="left" />
      <el-table-column prop="createdAt" :label="$t('message.createdAt')" width="180" align="left" header-align="left">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.actions')" width="250" align="left" header-align="left">
        <template #default="scope">
          <el-button size="small" @click="viewOrder(scope.row)">{{ $t('message.view') }}</el-button>
          <el-button size="small" @click="editOrder(scope.row)">{{ $t('message.edit') }}</el-button>
          <el-button 
            size="small" 
            :type="getActionTypeByStatus(scope.row.status)"
            @click="updateOrderStatus(scope.row)"
          >
            {{ getActionTextByStatus(scope.row.status) }}
          </el-button>
          <el-button size="small" type="danger" @click="deleteOrder(scope.row.orderId)">{{ $t('message.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      style="margin-top: 20px; text-align: right;"
    />
    
    <!-- 查看/编辑订单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="orderForm" :rules="orderRules" ref="orderFormRef" label-width="120px">
        <el-form-item :label="$t('message.userId')" prop="userId">
          <el-input 
            v-model="orderForm.userId" 
            :placeholder="$t('message.pleaseEnterUserId')"
            :disabled="isView"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.orderType')" prop="orderType">
          <el-select 
            v-model="orderForm.orderType" 
            :placeholder="$t('message.pleaseSelectOrderType')" 
            style="width: 100%"
            :disabled="isView"
          >
            <el-option
              v-for="type in orderTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.amount')" prop="amount">
          <el-input-number 
            v-model="orderForm.amount" 
            :min="0" 
            :precision="2"
            :step="0.01"
            :placeholder="$t('message.pleaseEnterAmount')"
            :disabled="isView"
            style="width: 100%"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('message.status')" prop="status">
          <el-select 
            v-model="orderForm.status" 
            :placeholder="$t('message.pleaseSelectStatus')" 
            style="width: 100%"
            :disabled="isView"
          >
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.transactionId')" prop="transactionId">
          <el-input 
            v-model="orderForm.transactionId" 
            :placeholder="$t('message.pleaseEnterTransactionId')"
            :disabled="isView"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer" v-if="!isView">
          <el-button @click="dialogVisible = false">{{ $t('message.cancel') }}</el-button>
          <el-button type="primary" @click="saveOrder">{{ $t('message.confirm') }}</el-button>
        </span>
        <span class="dialog-footer" v-else>
          <el-button type="primary" @click="dialogVisible = false">{{ $t('message.close') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

export default {
  name: 'OrderManagement',
  setup() {
    const { t } = useI18n();
    const authStore = useAuthStore();
    
    // 订单数据
    const orders = ref([]);
    
    // 筛选条件
    const filter = reactive({
      orderType: '',
      status: '',
      userId: ''
    });
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    });
    
    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const isEdit = ref(false);
    const isView = ref(false);
    
    // 表单数据
    const orderForm = reactive({
      orderId: '',
      userId: '',
      orderType: '',
      amount: 0,
      status: 'PENDING',
      transactionId: ''
    });
    
    const orderFormRef = ref();
    
    // 选项数据
    const orderTypes = ref([
      { value: 'COURSE', label: t('message.courseOrder') },
      { value: 'YOUBI', label: t('message.youbiOrder') },
      { value: 'OTHER', label: t('message.otherOrder') }
    ]);
    
    const statusOptions = ref([
      { value: 'PENDING', label: t('message.pending') },
      { value: 'PAID', label: t('message.paid') },
      { value: 'CANCELLED', label: t('message.cancelled') },
      { value: 'REFUNDED', label: t('message.refunded') }
    ]);
    
    // 表单验证规则
    const orderRules = {
      userId: [
        { required: true, message: t('message.pleaseEnterUserId'), trigger: 'blur' }
      ],
      orderType: [
        { required: true, message: t('message.pleaseSelectOrderType'), trigger: 'change' }
      ],
      amount: [
        { required: true, message: t('message.pleaseEnterAmount'), trigger: 'blur' },
        { type: 'number', min: 0, message: t('message.amountMustBePositive'), trigger: 'blur' }
      ],
      status: [
        { required: true, message: t('message.pleaseSelectStatus'), trigger: 'change' }
      ]
    };
    
    // 获取订单列表
    const loadOrders = async () => {
      try {
        // 构建查询参数
        const params = new URLSearchParams();
        params.append('page', pagination.currentPage);
        params.append('size', pagination.pageSize);
        
        if (filter.orderType) params.append('orderType', filter.orderType);
        if (filter.status) params.append('status', filter.status);
        if (filter.userId) params.append('userId', filter.userId);
        
        const response = await fetch(`/api/admin/orders?${params.toString()}`, {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          orders.value = data.items || data;
          pagination.total = data.total || orders.value.length;
        } else {
          ElMessage.error(t('message.failedToLoadOrders'));
        }
      } catch (error) {
        console.error('Error loading orders:', error);
        ElMessage.error(t('message.failedToLoadOrders'));
      }
    };
    
    // 重置筛选条件
    const resetFilters = () => {
      filter.orderType = '';
      filter.status = '';
      filter.userId = '';
      pagination.currentPage = 1;
      loadOrders();
    };
    
    // 打开添加订单对话框
    const openAddOrderDialog = () => {
      isEdit.value = false;
      isView.value = false;
      dialogTitle.value = t('message.addOrder');
      resetForm();
      dialogVisible.value = true;
    };
    
    // 查看订单
    const viewOrder = (order) => {
      isEdit.value = false;
      isView.value = true;
      dialogTitle.value = t('message.viewOrder');
      // 复制订单数据到表单
      Object.assign(orderForm, order);
      dialogVisible.value = true;
    };
    
    // 编辑订单
    const editOrder = (order) => {
      isEdit.value = true;
      isView.value = false;
      dialogTitle.value = t('message.editOrder');
      // 复制订单数据到表单
      Object.assign(orderForm, order);
      dialogVisible.value = true;
    };
    
    // 删除订单
    const deleteOrder = async (orderId) => {
      try {
        await ElMessageBox.confirm(
          t('message.confirmDeleteOrder'),
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        const response = await fetch(`/api/admin/orders/${orderId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          ElMessage.success(t('message.deleteOrderSuccess'));
          loadOrders(); // 重新加载订单
        } else {
          ElMessage.error(t('message.deleteOrderFailed'));
        }
      } catch (error) {
        console.error('Error deleting order:', error);
      }
    };
    
    // 更新订单状态
    const updateOrderStatus = async (order) => {
      try {
        let newStatus = '';
        let actionText = '';
        
        // 根据当前状态确定可执行的操作
        if (order.status === 'PENDING') {
          newStatus = 'PAID';
          actionText = t('message.pay');
        } else if (order.status === 'PAID') {
          newStatus = 'REFUNDED';
          actionText = t('message.refund');
        } else if (order.status === 'CANCELLED') {
          newStatus = 'PENDING';
          actionText = t('message.reactivate');
        } else {
          // 从PENDING回到PENDING，实际意义是重新激活
          newStatus = 'PENDING';
          actionText = t('message.reactivate');
        }
        
        await ElMessageBox.confirm(
          `${actionText} ${t('message.orderConfirm')}?`,
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        // 更新订单状态
        const response = await fetch(`/api/admin/orders/${order.orderId}/status`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ status: newStatus })
        });
        
        if (response.ok) {
          ElMessage.success(`${actionText}${t('message.successSuffix')}`);
          loadOrders(); // 重新加载订单
        } else {
          ElMessage.error(`${actionText}${t('message.failureSuffix')}`);
        }
      } catch (error) {
        console.error('Error updating order status:', error);
      }
    };
    
    // 保存订单
    const saveOrder = async () => {
      try {
        await orderFormRef.value.validate();
        
        let response;
        if (isEdit.value) {
          // 更新订单
          response = await fetch(`/api/admin/orders/${orderForm.orderId}`, {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(orderForm)
          });
        } else {
          // 创建订单
          response = await fetch('/api/admin/orders', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(orderForm)
          });
        }
        
        if (response.ok) {
          ElMessage.success(isEdit.value ? t('message.updateOrderSuccess') : t('message.addOrderSuccess'));
          dialogVisible.value = false;
          loadOrders(); // 重新加载订单
        } else {
          const errorData = await response.json();
          ElMessage.error(errorData.message || (isEdit.value ? t('message.updateOrderFailed') : t('message.addOrderFailed')));
        }
      } catch (error) {
        console.error('Error saving order:', error);
        ElMessage.error(isEdit.value ? t('message.updateOrderFailed') : t('message.addOrderFailed'));
      }
    };
    
    // 重置表单
    const resetForm = () => {
      Object.assign(orderForm, {
        orderId: '',
        userId: '',
        orderType: '',
        amount: 0,
        status: 'PENDING',
        transactionId: ''
      });
    };
    
    // 获取订单类型标签
    const getOrderTypeLabel = (orderType) => {
      const type = orderTypes.value.find(t => t.value === orderType);
      return type ? type.label : orderType;
    };
    
    // 获取状态标签
    const getStatusLabel = (status) => {
      const statusOption = statusOptions.value.find(s => s.value === status);
      return statusOption ? statusOption.label : status;
    };
    
    // 获取状态类型（用于标签样式）
    const getStatusType = (status) => {
      switch (status) {
        case 'PENDING': return 'warning';
        case 'PAID': return 'success';
        case 'CANCELLED': return 'info';
        case 'REFUNDED': return 'danger';
        default: return 'info';
      }
    };
    
    // 根据状态获取操作类型
    const getActionTypeByStatus = (status) => {
      switch (status) {
        case 'PENDING': return 'success';
        case 'PAID': return 'danger';
        case 'CANCELLED': return 'warning';
        case 'REFUNDED': return 'warning';
        default: return 'primary';
      }
    };
    
    // 根据状态获取操作文本
    const getActionTextByStatus = (status) => {
      switch (status) {
        case 'PENDING': return t('message.pay');
        case 'PAID': return t('message.refund');
        case 'CANCELLED': return t('message.reactivate');
        case 'REFUNDED': return t('message.reactivate');
        default: return t('message.update');
      }
    };
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    };
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      pagination.currentPage = 1;
      loadOrders();
    };
    
    const handleCurrentChange = (page) => {
      pagination.currentPage = page;
      loadOrders();
    };
    
    onMounted(() => {
      loadOrders();
    });
    
    return {
      orders,
      filter,
      pagination,
      dialogVisible,
      dialogTitle,
      orderForm,
      orderFormRef,
      orderRules,
      orderTypes,
      statusOptions,
      openAddOrderDialog,
      viewOrder,
      editOrder,
      deleteOrder,
      updateOrderStatus,
      saveOrder,
      resetFilters,
      loadOrders,
      getOrderTypeLabel,
      getStatusLabel,
      getStatusType,
      getActionTypeByStatus,
      getActionTextByStatus,
      formatDate,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.order-filters {
  margin-bottom: 20px;
}

.order-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>